package cn.ainit.yz.clinStore;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import cn.ainit.sys.common.dao.BusinessBaseDao;
import cn.ainit.sys.utils.UUID32;
import cn.ainit.yz.clinStore.entity.ClinStock;
import cn.ainit.yz.clinStore.entity.ClinStockItem;
@Transactional
@Repository
public class ClinStockDaoImpl extends BusinessBaseDao implements ClinStockDao {

	@Override
	public boolean saveClinStock(ClinStock clinStock,
			List<ClinStockItem> clinStockItems) throws Exception {
		this.getSessionFactory().getCurrentSession().save(clinStock);
		for (int i = 0; i < clinStockItems.size(); i++) {
			clinStockItems.get(i).setInItemId(UUID32.newGuid());
			clinStockItems.get(i).setInId(clinStock.getInId());
			this.getSessionFactory().getCurrentSession().save(clinStockItems.get(i));
		}
		return true;
	}

	@Override
	public boolean updClinStock(ClinStock clinStock,
			List<ClinStockItem> clinStockItems) throws Exception {
		List<ClinStockItem> oldItems = new ArrayList<ClinStockItem>();
		List<ClinStockItem> newItems = new ArrayList<ClinStockItem>();
		//更新操作
		//保存
		//缓存旧的明细IDS
		StringBuffer spItemIdS = new StringBuffer("");
		//遍历明细   判断条件
		for (int i = 0; i < clinStockItems.size(); i++) {
			//如果有主键，则是原有记录   拼接原有记录id 否则为新记录
			if (clinStockItems.get(i).getInItemId() != null && !clinStockItems.get(i).getInItemId().equals("")) {
				oldItems.add(clinStockItems.get(i));
				spItemIdS.append("'"+clinStockItems.get(i).getInItemId()+"',");
			}else {
				newItems.add(clinStockItems.get(i));
			}
		}
		String ids = spItemIdS.toString();
		if (!ids.equals("")) {
			ids = ids.substring(0, ids.length()-1);
		}
		//先删除不存在的
		if (!ids.trim().equals("")) {
			String sql = " delete from yz_cl_instock_item spi where spi.in_id = '"+clinStock.getInId()+"' ";
			sql += " and spi.IN_ITEM_ID not in ("+ids+") ";
//			System.out.println(sql);
			this.getJdbcTemplate().execute(sql);
		}
		//更新主表
		this.getSessionFactory().getCurrentSession().update(clinStock);
		//更新明细
		for (int i = 0; i < oldItems.size(); i++) {
			this.getSessionFactory().getCurrentSession().update(oldItems.get(i));
		}
		//更新主表
		for (int i = 0; i < newItems.size(); i++) {
			newItems.get(i).setInItemId(UUID32.newGuid());
			newItems.get(i).setInId(clinStock.getInId());
			this.getSessionFactory().getCurrentSession().save(newItems.get(i));
		}
		return true;
	}

}
